package com.applink.sell_proof.fragment;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.BasePagerActivity;
import com.applink.sell_proof.EMarketing;
import com.applink.sell_proof.R;
import com.applink.sell_proof.adapter.RewardProjectConfigAdapter;
import com.applink.sell_proof.adapter.RewardProjectDetailConfigAdapter;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.database.table.RewardProjectDBHelper;
import com.applink.sell_proof.database.table.RewardProjectDetailDBHelper;
import com.applink.sell_proof.pojo.GenericObject;
import com.applink.sell_proof.share.Parameter;
import com.applink.sell_proof.util.Utility;
import com.applink.sell_proof.utilConvertCount.GenericCounter;
import com.applink.sell_proof.utilConvertCount.GenericFilter;
import com.applink.sell_proof.utilXMLParser.ColumnSetting;
import com.applink.sell_proof.utilXMLParser.DesignFormatParser;
import com.applink.sell_proof.utilXMLParser.ObjPropInfo;
import com.applink.sell_proof.utilXMLParser.ObjectFormatParser;

public class RewardProjectFragment extends SherlockFragment implements OnItemSelectedListener{
	
	protected ViewGroup mLayout;
	private View mHeaderReward;
	private static final int SHOW_DATA = 0;
	
	private RewardProjectConfigAdapter mAdapter;
	private ListView listRewardProject;
	private TextView txtTotal;
	private Spinner spinner_Project;
	private ArrayList<ObjPropInfo> objPropList = new ArrayList<ObjPropInfo> ();
	private ArrayList<GenericObject> genericObjectList = new ArrayList<GenericObject>();
	private ArrayList<ColumnSetting> columnSettingList = new  ArrayList<ColumnSetting>();
	private boolean flag = false;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {		
		init(inflater,container);
		setHasOptionsMenu(true);
		((BasePagerActivity)getActivity()).showProgressDialog(R.id.reward_statement_container_loading);
		return mLayout;
	}
	
	private class loadData extends AsyncTask<Void, Void, Integer>{

		@Override
		protected Integer doInBackground(Void... params) {			
			DataHelper.getInstance().getRewardProject();
			DataHelper.getInstance().getRewardProjectDetail();
			return 0;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			mHandler.sendEmptyMessage(SHOW_DATA);
			super.onPostExecute(result);
		}		
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		new loadData().execute();
	}
	
	private Handler mHandler = new Handler(new Handler.Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case SHOW_DATA:
				((BasePagerActivity)getActivity()).hideProgressDialog(R.id.reward_statement_container_loading);

				if(flag){
					genericObjectList = Utility.convertProjectPojosIntoProjectGenericObjects(Utility.mDataProject,objPropList);
				}else{
					genericObjectList = RewardProjectDBHelper.getObjectBasedConfig(objPropList);
				}
				
				System.out.println(">>>>Reward genericObjectList = " + genericObjectList.size() );
				if(genericObjectList.size() == 0){
					return false;
				}
			
				if(mAdapter == null){
					String totalAmount = GenericCounter.getSumValueFromAnAttribute(genericObjectList, RewardProjectDBHelper.RW_PJ_TOTAL_REWARD_AMOUNT);
					txtTotal.setText(String.valueOf(totalAmount));	
					mAdapter = new RewardProjectConfigAdapter(EMarketing.getInstance().getApplicationContext(),genericObjectList,columnSettingList);
					listRewardProject.setAdapter(mAdapter);					
				}else{
					mAdapter.notifyDataSetChanged();
				}
				break;

			default:
				break;
			}
			return false;
		}
	});
	
	
	private void init(LayoutInflater inflater,ViewGroup container){
		
		//set for listview
		if(mLayout == null){
			mLayout = (ViewGroup) inflater.inflate(R.layout.reward_statement, null, false);
		}
		if(listRewardProject == null){
			listRewardProject = (ListView) mLayout.findViewById(R.id.list_reward_statement);
		}
		mHeaderReward = inflater.inflate(R.layout.header_reward_project, null);
		if(txtTotal == null){
			txtTotal = (TextView) mHeaderReward.findViewById(R.id.total_reward_project); 
		}
		
		// get dataobj and rptr of this list
		objPropList = ObjectFormatParser.ParserIntoObjProp(EMarketing.getInstance().getApplicationContext(),"contentData_RewardProject.xml",Parameter.OBJ_PROP_TAGNAME,"Rewards");		
		//objPropList = ObjectFormatParser.ParserIntoObjProp(EMarketing.getInstance().getApplicationContext(),"contentData_ProjectRewards.xml",Parameter.OBJ_PROP_TAGNAME,"Rewards");		
		columnSettingList = DesignFormatParser.ParserIntoColumnSetting(EMarketing.getInstance().getApplicationContext(),"rptrDesign_ProjectRewards.xml",Parameter.COL_TAGNAME);	
	
		//set for drop down list 
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				getActivity(), R.array.reward_project, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		if(spinner_Project == null){
			spinner_Project =(Spinner) mHeaderReward.findViewById(R.id.spinner_reward_project);
			spinner_Project.setOnItemSelectedListener(this);
		}
		spinner_Project.setAdapter(adapter);
		
		//set for listview
		listRewardProject.addHeaderView(mHeaderReward);
		listRewardProject.setVisibility(View.VISIBLE);
		listRewardProject.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {	
				
				//get position and get "ObjectID" of current clicked View by get Tag
				int objectID = Integer.parseInt(arg1.getTag().toString());
				//jump to new activity
				//parse newDataContent file
				
				ArrayList<ObjPropInfo> objPropListDetail =  ObjectFormatParser.ParserIntoObjProp(EMarketing.getInstance().getApplicationContext(),"contentData_RewardProjectDetail.xml",Parameter.OBJ_PROP_TAGNAME,"Rewards");					
				ArrayList<GenericObject>  genericObjectDetailList = null;
				if(flag){
					genericObjectDetailList = Utility.convertProjectPojosIntoProjectGenericObjects(Utility.mDataProjectDetails,objectID,objPropListDetail);
				}
				else{
					genericObjectDetailList = RewardProjectDetailDBHelper.loadObjectListByID(objectID, objPropListDetail);	
				}
				showPopUpDetails(genericObjectDetailList);
				flag = false;
				//Toast.makeText(EMarketing.getInstance().getApplicationContext(), "You selected: " + String.valueOf(objectID), Toast.LENGTH_LONG).show();
			}
		});
		
		
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
		
		((TextView) arg0.getChildAt(0)).setTextColor(Color.BLACK);
		if(genericObjectList == null || genericObjectList.size() == 0){
			return;
		}
		else{
			
			String quarter;
			switch(position){	
				case 0: quarter = ""; break;
				case 1: quarter = "Q1"; break;
				case 2: quarter = "Q2"; break;
				case 3: quarter = "Q3";break;
				case 4: quarter = "Q4"; break;
				default: quarter = ""; break;
			}
			//here we filter new genericObjectList based on a selected Quarter
			ArrayList<GenericObject> subGenericObjectList = GenericFilter.getSubGenericObjectListFromAnAttribute(genericObjectList,RewardProjectDBHelper.RW_PJ_QUARTER,"",quarter,"");
			mAdapter = new RewardProjectConfigAdapter(EMarketing.getInstance().getApplicationContext(),subGenericObjectList,columnSettingList);
		
			((ListView) mLayout.findViewById(R.id.list_reward_statement)).setAdapter(mAdapter);
			
			//we also set again total amount
			String totalAmount = GenericCounter.getSumValueFromAnAttribute(subGenericObjectList, RewardProjectDBHelper.RW_PJ_TOTAL_REWARD_AMOUNT);
			txtTotal.setText(String.valueOf(totalAmount));		
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		
	}
	
	private void showPopUpDetails(ArrayList<GenericObject>  genericObjectDetailList) {
		
		if(genericObjectDetailList.size() == 0) {
			Toast.makeText(EMarketing.getInstance().getApplicationContext(), "There is no entry data", Toast.LENGTH_LONG).show();
			return;
		}
		LayoutInflater layoutInflater = (LayoutInflater) getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				
		View popupView = layoutInflater.inflate(R.layout.reward_project_details, null);
		
		//get ListView and show its adapter
		ListView listRewardProjectDetail = (ListView) popupView.findViewById(R.id.list_reward_project_details);
		ArrayList<ColumnSetting> columnSettingDetailList = DesignFormatParser.ParserIntoColumnSetting(EMarketing.getInstance().getApplicationContext(),"rptrDesign_ProjectDetailRewards.xml",Parameter.COL_TAGNAME);	
		
		RewardProjectDetailConfigAdapter mDetailAdapter = new RewardProjectDetailConfigAdapter(EMarketing.getInstance().getApplicationContext(),genericObjectDetailList,columnSettingDetailList);
		
		listRewardProjectDetail.setAdapter(mDetailAdapter);		
		
		Button submit = (Button) popupView.findViewById(R.id.btn_reward_project_details);
		submit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dismissPopUpDetails();
			}
		});
	
		
		Utility.popupWindow = new PopupWindow(popupView,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		Utility.popupWindow.showAtLocation(mLayout, Gravity.CENTER, 0, 0);
	}
	
	private void dismissPopUpDetails(){
		if (Utility.popupWindow != null && Utility.popupWindow.isShowing()) {
			Utility.popupWindow.dismiss();
			Utility.popupWindow = null;
		}
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.reward_update_project, menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_reward_update_project:
			flag = true;
			mAdapter = null;
			new AsyncTask<Void, Void, Integer>(){

				@Override
				protected Integer doInBackground(Void... params) {
					RewardProjectDBHelper.clearRewardProject();
					RewardProjectDetailDBHelper.clearProjectDetail();		
					DataHelper.getInstance().getRewardProject();
					DataHelper.getInstance().getRewardProjectDetail();
					return 0;
				}
				
				@Override
				protected void onPostExecute(Integer result) {	
					super.onPostExecute(result);
					mHandler.sendEmptyMessage(SHOW_DATA);
				}
				
			}.execute((Void)null);
			break;

		default:
			break;
		}
//		if (item.getItemId() == R.id.menu_reward_update_project) {	
//			
//					
////			mAdapter = null;
////			new loadData().execute();
//			return true;
//		}
		return false;
	}
}
